<?php defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

/* JoomLeague League Management and Prediction Game for Joomla!
 * Copyright (C) 2007  Robert Moss
 *  
 * Homepage: http://www.joomleague.de
 * Support: htt://www.joomleague.de/forum/
 * 
 * This file is part of JoomLeague.
 *  
 * JoomLeague is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * Please note that the GPL states that any headers in files and
 * Copyright notices as well as credits in headers, source files
 * and output (screens, prints, etc.) can not be removed.
 * You can extend them with your own credits, though...
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * The "GNU General Public License" (GPL) is available at
 * http://www.gnu.org/copyleft/gpl.html.
*/ 

class TipRanking{
  
  var $project;
  var $mode;

  // constructor and member initialisation
  function TipRanking(){
    $this->project = null;
    $this->mode = 0;
  }
  
  // sets the project
  function setProject(&$project){
    $this->project = $project;
  }

  // method getTipRanking provides the TipRanking information
  // for showUser and showTipRanking Dialogs
  // supported params are
  // mode:
  //   "1" : Ranking only for the one round from param2
  //   all : Ranking for alls round until the round in param2
  //   optimal: Ranking for optimal matchday (last matchday with min one match played)
  // round:
  //   parameter round for calculation (see param1)
  // filter_uid:
  //   parameter to filter the information of one specific user
  //   it's helpful for showUser Information charts, because here 
  //   all TipRankings of all rounds until $round have to be build
  //   and stored to RAM.
  //   So it save RAM, if only the user Ranking of the requested user is stored
  
  function getTipRanking($mode, $round, $filter_uid = 0){
      
      // buid tipranking depending on requested mode
      $saisonEnde=0;
      if($mode == 'all')  {
        $query = "SELECT COUNT(r.id)                  
                    FROM #__joomleague_rounds r 
                   WHERE r.project_id = ".$this->project->id;
        $this->project->_db->setQuery($query);
        $gesamtrounds = $this->project->_db->loadResult();
        
        $rounds = $this->project->getRounds($round);
        $roundlist = implode(",",$rounds);
        
        if ($gesamtrounds==count($rounds)) $saisonEnde=1;
      }
      else
      {
        // try to get the optimal round
        // sysdate is used (MySQL 5.0.13, server offset is not implemented yet,
        // should be done soon)
        if ($mode == 'optimal') {
            $thistime=$this->project->getTimestamp('',1);
            $query = sprintf("SELECT max(matchcode)
                        FROM #__joomleague_matches m
                   LEFT JOIN #__joomleague_rounds r ON m.round_id = r.id
                       WHERE match_date <= '%s' AND
                             r.project_id = %s", date('Y-m-d H:i:s',$thistime), $this->project->id);
            $this->project->_db->setQuery($query);
            $round = $this->project->_db->loadResult();
        }
        
        // Work on round parameter "r", get a list of all match day for requested round
        $query = sprintf("SELECT id
                            FROM #__joomleague_rounds
                           WHERE matchcode = %s AND project_id = %s", $round,$this->project->id);
              
        $this->project->_db->setQuery($query);
        $rlist = $this->project->_db->loadResultArray();
        $roundlist = implode(",",$rlist);
      }
      
      return $this->buildTipRanking($roundlist, $filter_uid, $mode, $saisonEnde);
  }
  
  // internal calculation nethod to support getTipRanking method
  function buildTipRanking($roundlist, $filter_uid, $mode='', $saisonEnde=0){

      //ranking requested rounds

      $query = "SELECT count(m.match_id)
                 FROM #__joomleague_tip_results tip 
            LEFT JOIN #__joomleague_matches m on m.match_id = tip.match_id
            Left JOIN #__users u on u.id = tip.user_id
            LEFT JOIN #__joomleague_tip_members tm ON tm.user_id = tip.user_id  AND tm.project_id = m.project_id
                WHERE m.project_id = ".$this->project->id. " AND 
                      tm.approved = 1 AND 
                      m.round_id IN ($roundlist) 
             ORDER BY username DESC";

/***
      $query = "SELECT m.match_id,                  
                       m.matchpart1_result as e1,
                       m.matchpart2_result as e2,
                       m.alt_decision as decision,
                       m.matchpart1_result_decision AS v1,
                       m.matchpart2_result_decision AS v2,
                       m.round_id,
                       m.project_id,
                       tip.tip_home,
                       tip.tip_away,
                       tip.tip,
                       tip.joker,
                       u.username AS username,
                       u.id AS user_id
                 FROM #__joomleague_tip_results tip 
            LEFT JOIN #__joomleague_matches m on m.match_id = tip.match_id
            Left JOIN #__users u on u.id = tip.user_id
            LEFT JOIN #__joomleague_tip_members tm ON tm.user_id = tip.user_id  AND tm.project_id = m.project_id
                WHERE m.project_id = ".$this->project->id. " AND 
                      tm.approved = 1 AND 
                      m.round_id IN ($roundlist) 
             ORDER BY username DESC";
***/      
      // filter_uid is set for func,showTipResults/uid,62 use
      if ($filter_uid > 0) $query.= " AND u.id = $filter_uid";
      
      $this->project->_db->setQuery($query);
      $zeilen = $this->project->_db->loadResult();
      
      $queryoffset = 5000;
      
      $result = array();
        $query = "SELECT m.match_id,                  
                         m.matchpart1_result as e1,
                         m.matchpart2_result as e2,
                         m.alt_decision as decision,
                         m.matchpart1_result_decision AS v1,
                         m.matchpart2_result_decision AS v2,
                         m.round_id,
                         m.project_id,
                         tip.tip_home,
                         tip.tip_away,
                         tip.tip,
                         tip.joker,
                         u.username AS username,
                         u.id AS user_id
                   FROM #__joomleague_tip_results tip 
              LEFT JOIN #__joomleague_matches m on m.match_id = tip.match_id
              Left JOIN #__users u on u.id = tip.user_id
              LEFT JOIN #__joomleague_tip_members tm ON tm.user_id = tip.user_id  AND tm.project_id = m.project_id
                  WHERE m.project_id = ".$this->project->id. " AND 
                        tm.approved = 1 AND 
                        m.round_id IN ($roundlist) 
               ORDER BY username DESC LIMIT %s,%s";
      for($i=1;$i<=$zeilen; $i+=$queryoffset){
//        echo '<BR>'.$i.', <BR>';
//        flush();

        $this->project->_db->setQuery(sprintf($query,$i-1,$queryoffset));
        $rows = $this->project->_db->loadObjectList();
        
        foreach($rows as $row) {  
          if(!array_key_exists($row->user_id, $result)){
            $result[$row->user_id] = new TipMachine($this->project);
            $result[$row->user_id]->setUserName($row->username);
            $result[$row->user_id]->user_id = $row->user_id;
          }
          $result[$row->user_id]->addTip($row);

          // gefundene joker werden der tipmachine des users zugeteilt
          if ($row->joker==1) $result[$row->user_id]->setJokerMatch($row->match_id);
        }
        unset($rows);
      }

      if (($this->project->tip_champ==1) && ($mode=='all') && ($saisonEnde==1)) {
        $query = sprintf('SELECT COUNT(match_id)
                            FROM #__joomleague_matches 
                           WHERE (project_id=%s) AND (matchpart1_result is null and matchpart2_result is null) AND alt_decision=0',$this->project->id);
        $this->project->_db->setQuery($query);
        $offeneSpiele = $this->project->_db->loadResult();
        if ($offeneSpiele==0) {
          $table_config=$this->project->getTemplateConfig("show_table.tpl");
          $ranking = new Ranking();
          $ranking->setProjectConfig($this->project, $table_config['rankingorder']);
          $a = $ranking->getRanking(0, $this->project->current_round, 1, $table_config['show_negative_points'], $table_config['sort_table']);
          $merker = 0;
          foreach($a as $akey=>$aval){
            if ($merker==0) {
              $meister = $aval->team->teamtoolid;
              $merker = 1;
            }
          }
          foreach($result as $userid=>$user) {
            $query = sprintf('SELECT champ_tip
                                FROM #__joomleague_tip_members
                               WHERE (project_id=%s) AND user_id=%s',$this->project->id, $userid);
            $this->project->_db->setQuery($query);
            $champtip = $this->project->_db->loadResult();
            if ($champtip==$meister) {
              $result[$userid]->points += $this->project->tip_points_tip_champ;
            }
          }
        }
      }

      uasort($result, array ("TipMachine", "compare"));
      
      $rank=1;
      $previous_tipper = null;
      foreach ($result AS $key=>$val) {
        if ( ($previous_tipper != null) and ($val->compare($previous_tipper, $val)==0) ) {
          $result[$key]->rank = $previous_tipper->rank;
        } else {
          $result[$key]->rank = $rank;
        }
        $rank++;
        $previous_tipper=$result[$key];
      }
      
      return $result;
  }
  
}  

?>
